<template>
  <div class="question-parser">
    <el-card class="parser-card">
      <template #header>
        <div class="card-header">
          <h2>题目解析测试</h2>
          <div class="header-actions">
            <el-button type="primary" @click="parseQuestion" :loading="parsing">解析题目</el-button>
          </div>
        </div>
      </template>

      <div class="parser-content">
        <el-form :model="form" label-position="top">
          <el-form-item label="输入题目文本">
            <el-input
              v-model="form.questionText"
              type="textarea"
              :rows="10"
              placeholder="请输入题目文本，例如：马克思主义理论从狭义上说是（C） A、无产阶级争取自身解放和整个人类解放的学说体系 B、关于无产阶级斗争的性质、目的和解放条件的学说"
            />
          </el-form-item>
        </el-form>

        <!-- 多题目解析结果 -->
        <div v-if="allParsedQuestions && allParsedQuestions.length > 0" class="parsed-result">
          <h3>解析结果 (共{{ allParsedQuestions.length }}题)</h3>
          <el-divider />
          
          <el-collapse v-model="activeQuestions">
            <el-collapse-item 
              v-for="(question, index) in allParsedQuestions" 
              :key="index"
              :title="`第${index + 1}题: ${getQuestionTitle(question)}`"
              :name="index"
            >
              <div class="question-preview">
                <div class="result-item">
                  <strong>题目类型：</strong>
                  <el-tag :type="getQuestionTypeTag(question.question_type)">
                    {{ question.question_type || '未分类' }}
                  </el-tag>
                </div>
                
                <div class="result-item">
                  <strong>题目内容：</strong>
                  <div class="content-box">{{ getQuestionContent(question) }}</div>
                </div>
                
                <div class="result-item options-grid" v-if="question.options && Object.keys(question.options).length > 0">
                  <strong>选项：</strong>
                  <div class="options-container">
                    <div 
                      v-for="(content, letter) in question.options" 
                      :key="letter"
                      class="option-item"
                      :class="{'correct-option': question.detected_answer && question.detected_answer.includes(letter)}"
                    >
                      <span class="option-letter">{{ letter }}.</span>
                      <span class="option-content">{{ content }}</span>
                    </div>
                  </div>
                </div>
                
                <div class="result-item" v-if="question.detected_answer">
                  <strong>检测到的答案：</strong>
                  <el-tag type="success">{{ question.detected_answer }}</el-tag>
                </div>
                
                <div class="result-item" v-if="question.question_number">
                  <strong>题目编号：</strong>
                  <span>{{ question.question_number }}</span>
                </div>
              </div>
              
              <!-- 练习题预览 -->
              <div class="exercise-preview">
                <h4>练习题预览</h4>
                <div class="exercise-container">
                  <div class="exercise-question">
                    <div class="question-content">
                      <h3>{{ getQuestionContent(question) }}</h3>
                      <div class="question-meta">
                        <el-tag :type="getQuestionTypeTag(question.question_type)" size="small">
                          {{ question.question_type || '未分类' }}
                        </el-tag>
                      </div>
                    </div>
                    
                    <div class="options-list" v-if="question.options && Object.keys(question.options).length > 0">
                      <div 
                        v-for="(content, letter) in question.options" 
                        :key="letter"
                        class="option-item"
                        :class="{'correct-option': question.detected_answer && question.detected_answer.includes(letter)}"
                      >
                        <el-radio 
                          v-if="question.question_type === '单选题'"
                          v-model="previewAnswer"
                          :label="letter"
                        >
                          {{ letter }}. {{ content }}
                        </el-radio>
                        <el-checkbox 
                          v-else
                          v-model="previewMultiAnswer[letter]"
                        >
                          {{ letter }}. {{ content }}
                        </el-checkbox>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        
        <!-- 单题目解析结果 -->
        <div v-else-if="parsedQuestion" class="parsed-result">
          <h3>解析结果</h3>
          <el-divider />
          
          <div class="question-preview">
            <div class="result-item">
              <strong>题目类型：</strong>
              <el-tag :type="getQuestionTypeTag(parsedQuestion.question_type)">
                {{ parsedQuestion.question_type || '未分类' }}
              </el-tag>
            </div>
            
            <div class="result-item">
              <strong>题目内容：</strong>
              <div class="content-box">{{ getQuestionContent(parsedQuestion) }}</div>
            </div>
            
            <div class="result-item options-grid" v-if="parsedQuestion.options && Object.keys(parsedQuestion.options).length > 0">
              <strong>选项：</strong>
              <div class="options-container">
                <div 
                  v-for="(content, letter) in parsedQuestion.options" 
                  :key="letter"
                  class="option-item"
                  :class="{'correct-option': parsedQuestion.detected_answer && parsedQuestion.detected_answer.includes(letter)}"
                >
                  <span class="option-letter">{{ letter }}.</span>
                  <span class="option-content">{{ content }}</span>
                </div>
              </div>
            </div>
            
            <div class="result-item" v-if="parsedQuestion.detected_answer">
              <strong>检测到的答案：</strong>
              <el-tag type="success">{{ parsedQuestion.detected_answer }}</el-tag>
            </div>
            
            <div class="result-item" v-if="parsedQuestion.question_number">
              <strong>题目编号：</strong>
              <span>{{ parsedQuestion.question_number }}</span>
            </div>
          </div>
          
          <!-- 练习题预览 -->
          <div class="exercise-preview">
            <h4>练习题预览</h4>
            <div class="exercise-container">
              <div class="exercise-question">
                <div class="question-content">
                  <h3>{{ getQuestionContent(parsedQuestion) }}</h3>
                  <div class="question-meta">
                    <el-tag :type="getQuestionTypeTag(parsedQuestion.question_type)" size="small">
                      {{ parsedQuestion.question_type || '未分类' }}
                    </el-tag>
                  </div>
                </div>
                
                <div class="options-list" v-if="parsedQuestion.options && Object.keys(parsedQuestion.options).length > 0">
                  <div 
                    v-for="(content, letter) in parsedQuestion.options" 
                    :key="letter"
                    class="option-item"
                    :class="{'correct-option': parsedQuestion.detected_answer && parsedQuestion.detected_answer.includes(letter)}"
                  >
                    <el-radio 
                      v-if="parsedQuestion.question_type === '单选题'"
                      v-model="previewAnswer"
                      :label="letter"
                    >
                      {{ letter }}. {{ content }}
                    </el-radio>
                    <el-checkbox 
                      v-else
                      v-model="previewMultiAnswer[letter]"
                    >
                      {{ letter }}. {{ content }}
                    </el-checkbox>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import http from '../utils/axios'

const form = ref({
  questionText: ''
})

const parsing = ref(false)
const parsedQuestion = ref(null)
const allParsedQuestions = ref(null)
const activeQuestions = ref([0]) // 默认展开第一个题目
const previewAnswer = ref('')
const previewMultiAnswer = reactive({
  A: false,
  B: false,
  C: false,
  D: false,
  E: false
})

// 获取题目标题（用于折叠面板标题）
const getQuestionTitle = (question) => {
  if (!question) return '';
  
  // 如果有题目编号，使用编号
  if (question.question_number) {
    return `${question.question_number}. ${getQuestionContent(question).substring(0, 30)}...`;
  }
  
  // 否则使用题目内容的前30个字符
  return `${getQuestionContent(question).substring(0, 40)}...`;
}

// 获取题目内容（不包含选项）
const getQuestionContent = (question) => {
  if (!question) return '';
  
  // 如果有选项，从内容中提取不包含选项的部分
  if (question.options && Object.keys(question.options).length > 0) {
    // 尝试从content中提取不包含选项的部分
    const content = question.content.split('\n')[0];
    return content;
  }
  
  return question.content;
}

// 解析题目
const parseQuestion = async () => {
  if (!form.value.questionText.trim()) {
    ElMessage.warning('请输入题目文本')
    return
  }
  
  try {
    parsing.value = true
    allParsedQuestions.value = null
    parsedQuestion.value = null
    previewAnswer.value = ''
    
    // 重置多选答案
    Object.keys(previewMultiAnswer).forEach(key => {
      previewMultiAnswer[key] = false
    })
    
    // 调用后端API解析题目
    const response = await http.post('/parser/parse-text/', {
      text: form.value.questionText
    })
    
    if (response.data && response.data.success) {
      // 检查是否有多个题目
      if (response.data.all_questions && response.data.all_questions.length > 0) {
        allParsedQuestions.value = response.data.all_questions
        
        // 如果检测到答案，设置预览中的选中状态
        if (allParsedQuestions.value[0].detected_answer) {
          if (allParsedQuestions.value[0].question_type === '单选题') {
            previewAnswer.value = allParsedQuestions.value[0].detected_answer
          } else {
            // 多选题
            const answers = allParsedQuestions.value[0].detected_answer.split('')
            answers.forEach(letter => {
              previewMultiAnswer[letter] = true
            })
          }
        }
        
        ElMessage.success(`成功解析出${response.data.all_questions.length}个题目`)
      } else {
        parsedQuestion.value = response.data.question
        
        // 如果检测到答案，设置预览中的选中状态
        if (parsedQuestion.value.detected_answer) {
          if (parsedQuestion.value.question_type === '单选题') {
            previewAnswer.value = parsedQuestion.value.detected_answer
          } else {
            // 多选题
            const answers = parsedQuestion.value.detected_answer.split('')
            answers.forEach(letter => {
              previewMultiAnswer[letter] = true
            })
          }
        }
        
        ElMessage.success('题目解析成功')
      }
    } else {
      ElMessage.error(response.data?.message || '题目解析失败')
    }
  } catch (error) {
    console.error('解析题目错误:', error)
    ElMessage.error(error.response?.data?.message || '题目解析失败')
    
    // 如果API调用失败，尝试本地解析
    parseQuestionLocally()
  } finally {
    parsing.value = false
  }
}

// 本地解析题目（如果后端API不可用）
const parseQuestionLocally = () => {
  if (!form.value.questionText.trim()) {
    ElMessage.warning('请输入题目文本')
    return
  }
  
  const text = form.value.questionText
  
  // 尝试匹配题目编号和内容
  const questionPatterns = [
    // 数字+点格式：1. 题目内容
    /^(\d+)\.\s+(.+?)(?=\s*[A-E][、.．:：]|\s*$)/s,
    // 中文数字+顿号格式：一、题目内容
    /^([一二三四五六七八九十]+)[、.．]\s*(.+?)(?=\s*[A-E][、.．:：]|\s*$)/s,
    // 带括号的数字：(1) 题目内容
    /^[（\(]\s*(\d+)\s*[）\)]\s*(.+?)(?=\s*[A-E][、.．:：]|\s*$)/s,
    // 第X题格式：第一题 题目内容
    /^第([一二三四五六七八九十\d]+)题\s*(.+?)(?=\s*[A-E][、.．:：]|\s*$)/s
  ]
  
  let questionNumber = null
  let questionContent = null
  
  // 尝试匹配题目编号和内容
  for (const pattern of questionPatterns) {
    const match = text.match(pattern)
    if (match) {
      questionNumber = match[1]
      questionContent = match[2].trim()
      break
    }
  }
  
  // 如果没有匹配到题目格式，尝试直接提取题目内容
  if (!questionContent) {
    // 尝试查找第一个选项的位置
    const optionMatch = text.match(/[A-E][、.．:：]/)
    if (optionMatch) {
      const startPos = optionMatch.index
      questionContent = text.substring(0, startPos).trim()
    } else {
      // 如果没有找到选项，整个文本可能就是题目
      questionContent = text.trim()
    }
  }
  
  // 提取选项
  const options = {}
  const optionPatterns = [
    /([A-E])[、.．:：]\s*([^A-E]+?)(?=\s*[A-E][、.．:：]|\s*$)/gs,
    /([A-E])\.\s+([^A-E]+?)(?=\s*[A-E]\.\s+|\s*$)/gs,
    /([A-E])\s*[.．、:：]\s*([^A-E]+?)(?=\s*[A-E]\s*[.．、:：]|\s*$)/gs
  ]
  
  for (const pattern of optionPatterns) {
    let optionMatch
    let found = false
    
    while ((optionMatch = pattern.exec(text)) !== null) {
      const optionLetter = optionMatch[1].toUpperCase()
      const optionContent = optionMatch[2].trim()
      options[optionLetter] = optionContent
      found = true
    }
    
    if (found) break
  }
  
  // 检测答案
  let detectedAnswer = null
  
  // 匹配(.AB)格式的答案
  const multiAnswerPattern = /[（\(]\s*\.\s*([A-E]+)\s*[）\)]/i
  const multiAnswerMatch = text.match(multiAnswerPattern)
  
  if (multiAnswerMatch) {
    detectedAnswer = multiAnswerMatch[1].toUpperCase()
  } else {
    // 匹配(A)格式的答案
    const answerPattern = /[（\(]\s*([A-E])\s*[）\)]/i
    const answerMatch = text.match(answerPattern)
    
    if (answerMatch) {
      detectedAnswer = answerMatch[1].toUpperCase()
    } else {
      // 匹配(AB)格式的答案
      const directMultiAnswerPattern = /[（\(]\s*([A-E]{2,})\s*[）\)]/i
      const directMultiAnswerMatch = text.match(directMultiAnswerPattern)
      
      if (directMultiAnswerMatch) {
        detectedAnswer = directMultiAnswerMatch[1].toUpperCase()
      }
    }
  }
  
  // 构建完整的题目内容，包括选项
  let fullContent = questionContent || text
  
  // 确定题目类型
  let questionType = "选择题"
  if (text.includes("单项选择题") || text.includes("单选题")) {
    questionType = "单选题"
  } else if (text.includes("多项选择题") || text.includes("多选题")) {
    questionType = "多选题"
  } else if (detectedAnswer && detectedAnswer.length > 1) {
    questionType = "多选题"
  } else if (detectedAnswer && detectedAnswer.length === 1) {
    questionType = "单选题"
  }
  
  parsedQuestion.value = {
    content: fullContent,
    detected_answer: detectedAnswer,
    question_type: questionType,
    question_number: questionNumber,
    options: options
  }
  
  // 如果检测到答案，设置预览中的选中状态
  if (detectedAnswer) {
    if (questionType === '单选题') {
      previewAnswer.value = detectedAnswer
    } else {
      // 多选题
      const answers = detectedAnswer.split('')
      answers.forEach(letter => {
        previewMultiAnswer[letter] = true
      })
    }
  }
  
  ElMessage.success('题目解析成功（本地解析）')
}

// 获取题目类型的标签类型
const getQuestionTypeTag = (questionType) => {
  if (!questionType) return 'info'
  
  const typeMap = {
    '选择题': 'primary',
    '单选题': 'success',
    '多选题': 'warning',
    '判断题': 'info',
    '填空题': 'danger',
    '简答题': 'danger',
    '计算题': 'info',
    '分析题': 'info',
    '未分类': 'info'
  }
  return typeMap[questionType] || 'info'
}
</script>

<style scoped>
.question-parser {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.parser-card {
  margin-bottom: 20px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.parser-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.parsed-result {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.parsed-result h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.result-item {
  margin-bottom: 15px;
}

.content-box {
  background: rgba(255, 255, 255, 0.03);
  border-radius: 4px;
  padding: 10px;
  margin-top: 5px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.options-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
  margin-top: 10px;
}

.option-item {
  display: flex;
  padding: 8px;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.03);
  transition: all 0.3s;
}

.option-item:hover {
  background: rgba(255, 255, 255, 0.08);
}

.correct-option {
  background: rgba(103, 194, 58, 0.1);
  border-left: 3px solid var(--el-color-success);
}

.option-letter {
  font-weight: bold;
  margin-right: 8px;
  min-width: 20px;
}

.option-content {
  flex: 1;
}

.exercise-preview {
  margin-top: 30px;
  padding: 20px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.03);
  border: 1px dashed rgba(255, 255, 255, 0.2);
}

.exercise-preview h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: var(--el-color-primary);
}

.exercise-question {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.question-content {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.question-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.question-meta {
  display: flex;
  gap: 10px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .options-container {
    grid-template-columns: 1fr;
  }
}
</style> 